package com.zhoufy.api;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-04-19.
 *
 * @author chouFy
 */
public class CreateSession implements Watcher {


    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 回调方法 处理服务器端的watcher通知
     *
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 接触主程序countDownLatch 等待堵塞
            System.out.println("process method action");
            countDownLatch.countDown();
        }


        if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged ){
            System.out.println("节点发生变化");
        }


    }


    /**
     *  创建节点方法
     */
    public static void createNodeSync(int port) throws Exception{

        ZooKeeper zooKeeper = new ZooKeeper("localhost:2181", 5000, new CreateSession());
        System.out.println(zooKeeper.getState());

        countDownLatch.await();
        System.out.println(zooKeeper.getState());


        Stat stat = zooKeeper.exists("/zhoufy-persistent", true);

        if(stat == null) {
            zooKeeper.create("/zhoufy-persistent", ("localhost:" + port).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }

        zooKeeper.create("/zhoufy-persistent/localhost:" + port, ("localhost:" + port).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);



    }










    /**
     * 建立会话
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {


        createNodeSync(9095);
        /*
            客户端可以通过创建一个zk实例来连接zk服务器
            new Zookeeper(connectString, sessionTimeOut, Watcher);
            connectString : 连接地址 ip:端口
            sessionTimeOut  会话超时间 毫秒
            Watcher:   监听器(当特定事件触发监听 zk 会通过watcher通知到客户端)

         */


    }

}
